<template>
  <section>
    <el-form-item label="是否必填" v-if="selectWg.validate != null">
      <el-radio-group v-model="required" @on-change="onRequiredChange">
        <el-radio label="true">
            <span>是</span>
        </el-radio>
        <el-radio label="false">
            <span>否</span>
        </el-radio>
      </el-radio-group>
    </el-form-item>

    <el-form-item label="自定义校验规则(测试版本)" v-if="selectWg.validate != null">
      <el-input placeholder="请输入Validate表达式" v-model="validateJson" :rows="10" type="textarea" @on-blur="onBlur"></el-input>
    </el-form-item>
  </section>
</template>
<script>

export default {
  props: {
    selectWg: {
      type: Object
    }
  },
  data(){
    return {
      validate:'',
      required:'false'
    }
  },
  computed:{
    validateJson:{
      get:function(){
        var that = this
        var required = this.getRequired()
        if(required != null){
          this.required = String(required.required)
        }else{
          this.required = 'false'
        }
        var a = this.selectWg.key
        return JSON.stringify(this.selectWg.validate)
      },set:function(val){
        this.validate = val
      }
    }
  },
  methods:{
    getRequired(){
      var required = null
      this.selectWg.validate.forEach(function(item,index){
        if(item.required != null){
          required = item
          return
        }
      })
      return required
    },
    onRequiredChange(required){
      if(required == 'true'){
        var required = this.getRequired()
        if(required != null){
          required.required = true
        }else{
          this.selectWg.validate.push({required:true})
        }
        this.selectWg.validate = eval('(' + JSON.stringify(this.selectWg.validate) + ')')
      }else{
        var that = this
        var i = 0
        this.selectWg.validate.forEach(function(item,index){
          if(item.required){
            item.required = false
          }
        })
        this.selectWg.validate = eval('(' + JSON.stringify(this.selectWg.validate) + ')')
      }
    },
    onBlur(){
      try{
        if(this.validate.trim().length == 0){
          this.validate = ''
          this.selectWg.validate = []
          return
        }
        this.selectWg.validate = eval('(' + this.validate + ')')
      }catch(e){
        this.$Message['error']({
            background: true,
            content: '请输入正确的json表达式'
        });
      }
    }
  }
}
</script>
